unit KRK.Lib.CryptoAPI.Utilities;

{$WEAKPACKAGEUNIT ON}

interface

uses System.SysUtils, KRK.Lib.CryptoAPI.Types;

function GetStringCheckSum(const aInputString: String; aHashAlgorithms: array of THashAlgorithm; aFinalHashAlgorithm: THashAlgorithm = haIgnore): String;
function GetFileCheckSum(const aFileName: TFileName; aHashAlgorithms: array of THashAlgorithm; aFinalHashAlgorithm: THashAlgorithm = haIgnore): String;

implementation

uses System.Classes
   , KRK.Lib.CryptoAPI.MD2, KRK.Lib.CryptoAPI.MD4, KRK.Lib.CryptoAPI.MD5
   , KRK.Lib.CryptoAPI.SHA1, KRK.Lib.CryptoAPI.SHA256, KRK.Lib.CryptoAPI.SHA384
   , KRK.Lib.CryptoAPI.SHA512;

function GetStringCheckSum(const aInputString: String; aHashAlgorithms: array of THashAlgorithm; aFinalHashAlgorithm: THashAlgorithm = haIgnore): String;
var
  HashAlgorithm: THashAlgorithm;
begin
  Result := aInputString;

  for HashAlgorithm in aHashAlgorithms do
    case HashAlgorithm of
      haSha512: Result := SHA512ToString(SHA512Hash(RawByteString(Result)));
      haSha384: Result := SHA384ToString(SHA384Hash(RawByteString(Result)));
      haSha256: Result := SHA256ToString(SHA256Hash(RawByteString(Result)));
      haSha1: Result := SHA1ToString(SHA1Hash(RawByteString(Result)));
      haMd5: Result := MD5ToString(MD5Hash(RawByteString(Result)));
      haMd4: Result := MD4ToString(MD4Hash(RawByteString(Result)));
      haMd2: Result := MD2ToString(MD2Hash(RawByteString(Result)));
    end;

  if aFinalHashAlgorithm <> haIgnore then
    Result := GetStringCheckSum(Result, [aFinalHashAlgorithm]);
end;

function GetFileCheckSum(const aFileName: TFileName; aHashAlgorithms: array of THashAlgorithm; aFinalHashAlgorithm: THashAlgorithm = haIgnore): String;
var
  HashAlgorithm: THashAlgorithm;
  FS: TFileStream;
begin
  Result := aFileName;

  FS := TFileStream.Create(Result,fmOpenRead);
  try
    for HashAlgorithm in aHashAlgorithms do
      case HashAlgorithm of
        haSha512: Result := SHA512ToString(SHA512Hash(FS));
        haSha384: Result := SHA384ToString(SHA384Hash(FS));
        haSha256: Result := SHA256ToString(SHA256Hash(FS));
        haSha1: Result := SHA1ToString(SHA1Hash(FS));
        haMd5: Result := MD5ToString(MD5Hash(FS));
        haMd4: Result := MD4ToString(MD4Hash(FS));
        haMd2: Result := MD2ToString(MD2Hash(FS));
      end;
  finally
    FS.Free;
  end;

  if aFinalHashAlgorithm <> haIgnore then
    Result := GetFileCheckSum(Result, [aFinalHashAlgorithm]);
end;

end.
